package com.qf.cloud2204.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class TestZuulFilter2 extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;//前置过滤器，相对于微服务
    }

    @Override
    public int filterOrder() {
        return 4;//过滤器的序号，越小先执行
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取之前过滤器设置的sendZuulResponse得属性，如果之前的过滤器已经不想发送该请求了，
        // 那么这个过滤器也不进入run方法
        boolean b = currentContext.sendZuulResponse();

        return b;
    }

    @Override
    public Object run() throws ZuulException {

        //记录请求起始时间戳
        long start = System.currentTimeMillis();

        RequestContext currentContext = RequestContext.getCurrentContext();
        //把起始时间戳存入RequestContext对象中
        currentContext.set("time-start",start);

        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("token");
        if (!token.equals("123456")){
            currentContext.setSendZuulResponse(false);
            try {
                currentContext.getResponse().getWriter().println("token error");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
      //  System.out.println("!!!!!!!!");
        return null;
    }
}
